<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\TagCount;
use fast\Arr;
use function fast\array_get;
use fast\Http;
use GatewayWorker\Lib\Gateway;
use Redis;
use think\Cache;
use think\helper\Str;
use think\Request;

/**
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $first_uid   = 1000000;
    /**
     * @var Redis
     */
    protected $redis;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->redis = Cache::store("redis")->handler();
    }


    public function get_uid()
    {
        $tag     = input('tag');

        $info    = $this->generate_session_uid($tag);
        $address = get_address();
        $ip      = $info['ip'];
        $uid     = $info['uid'];
        $count   = $this->update_count($ip, $uid, $tag, array_get($address, 'province'), array_get($address, 'city'), true);
        $this->success('ok', [
            'uid'      => $info['uid'],
            'count'    => $count,
            'province' => array_get($address, 'province'),
//            'info'=>$info
        ]);
    }



    protected function generate_session_uid($tag)
    {
        $session_key = "$tag|count_ip";
        if (session($session_key)) {
            $info = session($session_key);
        } else {
            session($session_key, $info = ['ip' => $this->request->ip()]);
        }

        $redis = get_redis();
        //为访问用户生成uid
        if (!isset($info['uid'])) {
            if (!$redis->exists('uid_count')) {
                $redis->set('uid_count', 1000000);
            }
            $uid = $info['uid'] = $redis->get('uid_count');
            //用户uid数自增
            $redis->incr('uid_count');
            session($session_key, $info);
            //缓存uid信息到redis
            $redis->set("$uid|info", json_encode($info));
        }

        return $info;
    }

    public function tag_count()
    {
        $tag           = input('tag');
        $is_only_query = input('is_only_query') === 'true';
        if (!$tag) $this->error('tag必须');
        $info    = $this->generate_session_uid($tag);
        $address = get_address();
        $ip      = $info['ip'];
        $uid     = $info['uid'];
        $count   = $this->update_count($ip, $uid, $tag, array_get($address, 'province'), array_get($address, 'city'), $is_only_query);
        $this->success('ok', [
            'count'    => $count,
            'province' => array_get($address, 'province'),
            'info'=>$info
        ]);
    }

    public function rank()
    {
        $tag = input('tag');
        if (!$tag) $this->error('tag必须');
        $provinces = $this->redis->keys("provincecount|$tag|*");
        $ranks     = [];
        foreach ($provinces as $province_key) {
            $province = str_replace("provincecount|$tag|", '', $province_key);
            $ranks[]  = [
                'province' => $province,
                'count'    => intval($this->redis->get($province_key))
            ];
        }

//       array_multisort($ranks, array_column($ranks,'count'));
        array_multisort(array_column($ranks, 'count'), SORT_DESC, $ranks);
        if (!input('isall')) {
            $ranks = array_slice($ranks, 0, 10);
        }

        $this->success('ok', $ranks);
    }

    public function getGroupUid(){
        Gateway::$registerAddress='127.0.0.1:1560';
        $redis = get_redis();
       $client_sessions= Gateway::getClientSessionsByGroup(input('tag','klee_click'));
       foreach ($client_sessions as $client_id=>&$client_session){
           $uid   = $client_session['uid'];
           $info  = $redis->get("$uid|info");
           $info    = json_decode($info, true);
           $client_session['info']=$info;
           $client_session['address']=get_address($info['ip']);
       }
       $this->success('',$client_sessions);
    }

    public function city_rank()
    {
        $tag = input('tag');
        if (!$tag) $this->error('tag必须');
        $provinces = $this->redis->keys("citycount|$tag|*");
        $ranks     = [];
        foreach ($provinces as $province_key) {
            $province_city     = str_replace("citycount|$tag|", '', $province_key);
            $province_city_arr = explode('|', $province_city);
            $province          = array_get($province_city_arr, 0);
            $city              = array_get($province_city_arr, 1);
            $ranks[]           = [
                'province' => $province,
                'city'     => $city,
                'count'    => intval($this->redis->get($province_key))
            ];
        }

//       array_multisort($ranks, array_column($ranks,'count'));
        array_multisort(array_column($ranks, 'count'), SORT_DESC, $ranks);

        $ranks = array_slice($ranks, 0, 10);
        $this->success('ok', $ranks);
    }

    protected function update_count($ip, $uid, $tag, $province, $city, $is_get = false)
    {
        $ip  = ip2long($ip);
        $key = "$ip|$tag";
        if ($is_get) return intval($this->redis->get($key)) ?: 0;
        $count = $this->redis->incr($key);
        $this->redis->set("$uid|uid|$tag", "$count");
        $province_key = "provincecount|$tag|$province";
        $this->redis->incr($province_key);
        $city_key = "citycount|$tag|$province|$city";
        $this->redis->incr($city_key);

        $tagCount = TagCount::get(['ip' => $ip]);
        if (!$tagCount) {
            TagCount::create([
                'ip'    => $ip,
                'tag'   => $tag,
                'count' => $count,
            ]);
        } else {
            $tagCount['count'] = $count;
            $tagCount->save();
        }
        return $count;
    }

    public function fuck(){
        $url='http://www.aideapp.cn/user/getFile.php?fToken=e116ead735c2b176&fPassword=&type=Api/Wechat/Bind/bind_jiangshi';
        $response=Http::get($url);
        $response=json_decode($response,true);
        $info=$response['info'];
        $params=[
            'code'=>$info
        ];
        $result=Http::post("http://8.142.210.165/Api/Wechat/Bind/b",$params);
        echo $result;die;
//        $this->success('ok', get_address(input('ip')));
    }
    public function query_ip( ){
        // $ip=input('ip');
        //   $url= "http://ip-api.com/json/$ip?lang=zh-CN";
        //     $responseStr=\fast\Http::get($url);
        //     $response=json_decode($responseStr,true);
        //  $this->success('ok', $response);die;
        
         $this->success('ok', get_address(input('ip')));
    }
}
